.TH std::span::operator[] 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::span::operator[] \- std::span::operator[]

.SH Synopsis
   constexpr reference operator[]( size_type idx ) const;  \fI(since C++20)\fP

   Returns a reference to the idx^th element of the sequence. The behavior is undefined
   if idx is out of range (i.e., if it is greater than or equal to size()).

.SH Parameters

   idx - the index of the element to access

.SH Return value

   A reference to the idx^th element of the sequence, i.e., data()[idx].

.SH Exceptions

   Throws nothing.

.SH Example


// Run this code

 #include <cstddef>
 #include <iostream>
 #include <span>
 #include <utility>

 void reverse(std::span<int> span)
 {
     for (std::size_t i = 0, j = std::size(span); i < j; ++i)
     {
         --j;
         std::swap(span[i], span[j]);
     }
 }

 void print(std::span<const int> const span)
 {
     for (int element : span)
         std::cout << element << ' ';
     std::cout << '\\n';
 }

 int main()
 {
     int data[]{1, 2, 3, 4, 5};
     print(data);
     reverse(data);
     print(data);
 }

.SH Output:

 1 2 3 4 5
 5 4 3 2 1

.SH See also

   at                access specified element with bounds checking
   (C++26)           \fI(public member function)\fP
   data              direct access to the underlying contiguous storage
                     \fI(public member function)\fP
   size              returns the number of elements
                     \fI(public member function)\fP
   as_bytes          converts a span into a view of its underlying bytes
   as_writable_bytes \fI(function template)\fP
   (C++20)
